package com.iwjw.ibatis.generate.util;

import com.iwjw.ibatis.generate.model.FieldInfo;
import com.iwjw.ibatis.util.MySqlType2JavaType;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author: huangweiwei
 * @email: ihuangweiwei@163.com
 * @created:2016/10/26
 */
public class BuildTableInfoUtil {

    /**
     * 获取所有表名
     *
     * @param conn
     * @return
     */
    public static List<String> getTables(Connection conn) {
        List<String> tables = new ArrayList<String>();
        PreparedStatement pstate = null;
        try {
            pstate = conn.prepareStatement("show tables");
            ResultSet results = pstate.executeQuery();
            while (results.next()) {
                tables.add(results.getString(1));
            }
            return tables;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return Collections.emptyList();
    }


    /**
     * 获取字段信息
     *
     * @param tableName
     * @param connection
     * @return
     */
    public static List<FieldInfo> getFieldInfos(String tableName, Connection connection) {
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement("SHOW FULL FIELDS FROM " + tableName);
            ResultSet results = preparedStatement.executeQuery();
            List<FieldInfo> fieldInfos = new ArrayList<FieldInfo>();
            while (results.next()) {
                FieldInfo fieldInfo = new FieldInfo();
                fieldInfo.setField(results.getString("field"));
                fieldInfo.setCollation(results.getString("collation"));
                fieldInfo.setKey(results.getString("key"));
                String type = results.getString("type");
                if (type.contains("(")) {
                    type = type.substring(0, type.indexOf("("));
                }
                fieldInfo.setType(type);
                fieldInfo.setComment(results.getString("comment"));
                fieldInfo.setExtra(results.getString("extra"));
                fieldInfos.add(fieldInfo);
            }
            return fieldInfos;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return Collections.emptyList();
    }

    public static Class mysqlProcessType(String type) {


        return MySqlType2JavaType.get(type.toUpperCase());

    }


}
